<template src="./template.html"></template>

<script>
/* global moment */
import { PAGE_STATUS_INFO } from 'store/mutation-types'
import ResizeMixin from 'mixins/resize'
import { PAGE_CONFIG, FUN_IDS_OPTIONS } from 'common/consts'
import { COL_INDEXS, PASSING_STATE } from './consts'
import { getLessonUserExercise, exportRecord, exportFile } from '../models'
import { getCourseStuGroup } from '../../trainee/models'
import { getLessonFindList } from '../../lesson-period/models'

export default {
  mixins: [ResizeMixin],
  data() {
    return {
      COL_INDEXS,
      FUN_IDS_OPTIONS,
      PASSING_STATE,
      isPageLoading: false,

      lessonList: [],
      groupList: [],

      tableList: [],
      PAGE_CONFIG: PAGE_CONFIG,
      pageNo: PAGE_CONFIG.defaultPageNo,
      pageSize: PAGE_CONFIG.defaultPageSize,
      cachePageNo: 0,
      totalCount: 0,
      filterForm: {
        q: '',
        exerciseType: '',
        groupId: '',
        lessonId: '',
        passingState: ''
      },
    };
  },
  computed: {
    courseId() {
      return this.$route.query.courseId
    },
    userId() {
      return this.$route.query.userId
    },
    nickName() {
      return this.$route.query.nickName
    }
  },

  methods: {
    $handleReport(it) {
      this.$router.push({ name: 'curriculum.manager.report', params: { exerciseId: it.exerciseId } })
    },
    $search() {
      this.pageNo = 1
      this.$getTableList()
    },
    formatSecondsToMMSS(seconds) {
      // 创建时长对象
      const duration = moment.duration(seconds, 'seconds');
      // 分别获取分钟和秒数
      const mins = Math.floor(duration.asMinutes()); // 总分钟数（取整）
      const secs = duration.seconds(); // 剩余的秒数

      // 格式化为两位数 (如 5 -> "05")
      const formattedMins = mins.toString().padStart(2, '0');
      const formattedSecs = secs.toString().padStart(2, '0');

      return `${formattedMins}:${formattedSecs}`;
    },
    async $getTableList() {
      this.isPageLoading = true;
      // 判断是否有缓存的页码
      if (this.cachePageNo) {
        this.pageNo = this.cachePageNo
        this.cachePageNo = 0
      }
      const params = {
        ...this.filterForm,
        limit: this.pageSize,
        page: this.pageNo,
        courseId: this.courseId,
        userId: this.userId
      };
      try {
        const { data } = await getLessonUserExercise(params);
        this.tableList = (data.list || []).map(it => ({
          ...it,
          createTime: it.createTime && moment(it.createTime).format('YYYY-MM-DD HH:mm'),
          useTime: it.useTime && this.formatSecondsToMMSS(parseInt(it.useTime, 10))
        }))
        this.totalCount = data.total
        this.isPageLoading = false;
        console.log(this.pageNo)
      } catch (err) {
        this.isPageLoading = false;
        this.$message.error(err.message || err.message || '获取列表出错')
      }
    },
    $handlePageChange() {
      this.$getTableList();
    },
    async $getCourseStuGroup() {
      this.isPageLoading = true;
      const params = {
        limit: 99999,
        page: 1,
        courseId: this.courseId
      };
      try {
        const { data } = await getCourseStuGroup(params);
        this.groupList = data.list || []
        this.isPageLoading = false;
      } catch (err) {
        this.isPageLoading = false;
        this.$message.error(err.message || err.message || '获取列表出错')
      }
    },
    async $getLessonFindList() {
      this.isPageLoading = true;
      const params = {
        courseId: this.courseId
      };
      try {
        const { data } = await getLessonFindList(params);
        this.lessonList = data || []
        this.isPageLoading = false;
      } catch (err) {
        this.isPageLoading = false;
        this.$message.error(err.message || err.message || '获取列表出错')
      }
    },
    async $exportRecord() {
      this.isPageLoading = true
      const params = {
        ...this.filterForm,
        courseId: this.courseId
      }
      try {
        const response = await exportRecord(params)
        exportFile(response)
        this.isPageLoading = false
      } catch (err) {
        this.isPageLoading = false
        console.log(err)
        this.$message.error(err.message || '导出异常')
      }
    }
  },
  async created() {
    if (this.$store.state.pageStatusInfo.dataRecordAchievementParams) {
      this.pageSize = this.$store.state.pageStatusInfo.dataRecordAchievementParams.pageSize
      this.cachePageNo = this.$store.state.pageStatusInfo.dataRecordAchievementParams.pageNo
      for (const key in this.filterForm) {
        this.filterForm[key] = this.$store.state.pageStatusInfo.dataRecordAchievementParams[key]
      }
    }
    this.$store.commit(PAGE_STATUS_INFO, {
      dataRecordAchievementParams: null,
    })
    if (this.courseId) {
      await this.$getCourseStuGroup()
      await this.$getLessonFindList()
    }
    this.$getTableList();
  },
  beforeRouteLeave(to, from, next) {
    //
    const dataRecordAchievementParams = {
      ...this.filterForm,
      pageSize: this.pageSize,
      pageNo: this.pageNo,
    }
    if (/^curriculum\.manager\.report$/.test(to.name)) {
      // 建议key为当前页面的路由name + 其他，以防止和其他变量重复
      this.$store.commit(PAGE_STATUS_INFO, {
        dataRecordAchievementParams: dataRecordAchievementParams
      })
    }
    next()
  }
};
</script>
